package com.atguigu.reactor;

import java.util.ArrayList;
import java.util.Optional;
import java.util.Random;
import java.time.Duration;

import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

public class FluxMonoDemo {
    public static void main(String[] args) {
        System.out.println("Hello world!");
        fluxDemoSimpleCreate();
        fluxDemoComplexCreate();
        monoDemoSimpleCreate();
    }

    static void fluxDemoSimpleCreate() {
        Flux.just("hello", "world").subscribe(System.out::println);
        Flux.fromArray(new Integer[] { 1, 2, 3 }).subscribe(System.out::println);
        Flux.empty().subscribe(System.out::println);
        Flux.range(1, 10).subscribe(System.out::println);
        Flux.interval(Duration.ofSeconds(1), Duration.ofSeconds(2)).subscribe(System.out::println);
    }

    static void monoDemoSimpleCreate() {
        Mono.fromSupplier(() -> "29 --- hello").subscribe(System.out::println);
        Mono.justOrEmpty(Optional.of("30 --- hello")).subscribe(System.out::println);
        Mono.create(sink -> sink.success("31 --- hello")).subscribe(System.out::println);
    }

    static void fluxDemoComplexCreate() {
        Flux.generate(sink -> {
            sink.next("36 --- hello");
            sink.complete();
        }).subscribe(System.out::println);

        System.out.println("------------------- 393939");

        final Random random = new Random();
        Flux.generate(ArrayList::new, (list, sink) -> {
            int value = random.nextInt(100);
            list.add(value);
            sink.next(value);
            if (list.size() == 10) {
                sink.complete();
            }
            return list;
        }).parallel().subscribe(System.out::println);

        System.out.println("------------------- 525252");

        Flux.create(sink -> {
            for (int i = 100; i < 150; i++) {
                sink.next(i);
            }
            sink.complete();
        }).parallel().subscribe(System.out::println);
    }
}
